//
//  DeviceBarcodeScanViewController.m
//  sentorise
//
//  Created by admin on 2025/9/2.
//

#import "DeviceBarcodeScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "GlobalDefine.h"

@interface DeviceBarcodeScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

@end

@implementation DeviceBarcodeScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    
    [self setupCamera];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, StatusBarHeight, 44, 44)];
    [backBtn setImage:[UIImage imageNamed:@"scan_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(actionBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}

- (void)actionBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupCamera {
    // 1. 获取摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (!device) {
        NSLog(@"没有摄像头");
        return;
    }
    
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (error) {
        NSLog(@"摄像头不可用: %@", error.localizedDescription);
        return;
    }
    
    // 2. 会话
    self.session = [[AVCaptureSession alloc] init];
    [self.session addInput:input];
    
    // 3. 输出
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [self.session addOutput:output];
    
    // 4. 设置输出代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 支持的扫码类型（条形码/二维码）
    output.metadataObjectTypes = @[
        AVMetadataObjectTypeEAN13Code,
        AVMetadataObjectTypeEAN8Code,
        AVMetadataObjectTypeCode128Code,
        AVMetadataObjectTypeQRCode
    ];
    
    // 5. 预览图层
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = [UIScreen mainScreen].bounds;
    [self.view.layer addSublayer:self.previewLayer];
    
    // 6. 启动会话
    [self.session startRunning];
}

#pragma mark - 扫描结果回调
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects
       fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects.firstObject;
        NSString *result = obj.stringValue;
        NSLog(@"扫描结果: %@", result);
        // 停止扫描
        [self.session stopRunning];
        self.scanDown(result);
        [self.navigationController popViewControllerAnimated:YES];
    }
}


@end
